from flask import Flask, request, render_template, jsonify
from service.content_generator import generate_with_aliyun
from service.content_generator import generate_prompt
from service.page_generator import generate_html_pages
from service.get_image_list import sync_capture
from service.tts_service import TTSService
from service.video_generator import generate_video
import os
import json
from flask_cors import CORS  # 添加这行
from flask import send_from_directory
from flask import send_file
from flask import Response  # 新增导入Response对象
app = Flask(__name__)
CORS(app)  # 添加这行启用CORS
@app.route('/generate', methods=['POST'])
def generate_teaching_page():
    keyword = request.json.get('keyword')
    try:
        # 生成教学内容
        #content_prompt=generate_prompt(keyword,'content')
        #content_data = generate_with_aliyun(content_prompt)
        # 加载text文件
        config_dir = os.path.join(app.root_path, 'config')
        content_path = os.path.join(config_dir, 'json.txt')
        script_path=os.path.join(config_dir, 'script.txt')
        # 处理教学内容
        with open(content_path, 'r', encoding='utf-8') as f:
            try:
                res=f.read().lstrip('```json').rstrip('```')
                parsed_content = json.loads(res)  # 解析JSON数据，忽略多余的字符
            except json.JSONDecodeError as e:
                raise ValueError(f"JSON解析失败：{e}")
        #处理教学脚本
        with open(script_path, 'r', encoding='utf-8') as f:
            try:
                res=f.read().lstrip('```json').rstrip('```')
                parsed_script=json.loads(res)
            except json.JSONDecodeError as e:
                raise ValueError(f"JSON解析失败：{e}")
        
        # 生成HTML页面 
        pageList=generate_html_pages(parsed_content,'output/pages')
        # 将HTML页面逐帧截图
        screenshot_dirs=sync_capture(pageList, 'output/frames', 24)
        # 生成教学讲稿
        #script_prompt=generate_prompt(res,'script')
        #script_data = generate_with_aliyun(script_prompt)
        #生成音频文件
        ttsservice=TTSService()
        segments=ttsservice.text_to_speech(parsed_script, 'output/audio')
        # 生成视频文件
        video_path = os.path.abspath('output/teching_script.mp4')
        generate_video(segments, screenshot_dirs, video_path)
        return jsonify({
            'video_url': f'teching_script.mp4',
            'status': 'success'
        })
    except ValueError as ve:
        app.logger.error(f"输入数据异常: {ve}")
        return jsonify(error=f"参数错误: {ve}"), 400
    except json.JSONDecodeError as je:
        app.logger.error(f"JSON解析失败: {je.doc}")
        return jsonify(error="无效的响应格式"), 502



# 添加静态文件路由
@app.route('/api/download/<filename>')
def download_video(filename):
    output_dir = os.path.join(os.path.dirname(app.root_path), 'output')
    file_path = os.path.join(output_dir, filename)
    if not os.path.exists(file_path):
        return jsonify(error="视频文件未生成"), 404
    return send_from_directory(
        directory=output_dir,
        path=filename,
        as_attachment=False
    )

@app.route('/api/workflow/<workflow_id>')
def get_workflow_status(workflow_id):
    # 从Redis获取全流程状态
    # 实现伪代码示例:
    status = redis_conn.hgetall(f'workflow:{workflow_id}')
    return jsonify({
        "html_status": status.get('html', 'pending'),
        "screenshot_status": status.get('screenshots', 'pending'),
        "audio_status": status.get('audio', 'pending'),
        "video_status": status.get('video', 'pending')
    })
    

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=os.getenv('FLASK_DEBUG', False))